package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    /***
     * 登录方法
     * @param username
     * @param password
     * @param response
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result<String> login(String username, String password, HttpServletResponse response) {

        //1.用户数据校验
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }

        //2.登录
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //3.用户cookie放jti
        Cookie cookie = new Cookie("uid", authToken.getJti());
        cookie.setPath("/");
        cookie.setDomain(cookieDomain);
        cookie.setMaxAge(cookieMaxAge);
        cookie.setHttpOnly(false);

        response.addCookie(cookie);

        //4.返回
        return new Result(true, StatusCode.OK, "登陆成功", authToken.getJti());
    }

    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(value = "FROM", required = false, defaultValue = "") String from, Model model) throws Exception {
        model.addAttribute("from", from);
        return "login";
    }

    /***
     * 退出方法
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request,HttpServletResponse response) {
        authService.logout(request,response);
        return new Result(true, StatusCode.OK, "退出成功");
    }
}
